package org.example.Servlet.PersonServlet;

import org.example.Dao.PersonDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        System.out.println("===>username<====  ====> " + username);
        String password = req.getParameter("password");
        String confirmPassword = req.getParameter("confirmPassword");
        String email = req.getParameter("email");
        HttpSession session = req.getSession();
        //判断两次密码是否一致
        if (!password.equals(confirmPassword)) {
            session.setAttribute("registerMessage", "两次密码不一致");
            req.getRequestDispatcher("/views/register.jsp").forward(req, resp);
        }

        //判断该邮箱是否被注册过
        PersonDao personDao = new PersonDao();
        boolean emailExist = false;
        try {
            emailExist = personDao.isEmailExist(email);

        } catch (Exception e) {
            session.setAttribute("registerMessage", "服务器维护中");
            req.getRequestDispatcher("/views/register.jsp").forward(req, resp);
        }

        if (emailExist) {
            session.setAttribute("registerMessage", "该邮箱已被注册");
            req.getRequestDispatcher("/views/register.jsp").forward(req, resp);
        }

        //开始注册
        try {
            boolean isRegister = personDao.register(username, password, email);

            //注册成功
            if (isRegister) {
                session.setAttribute("registerMessage", "注册成功，请跳转到登录页面");
                resp.sendRedirect(req.getContextPath() + "/views/register.jsp");
            } else {
                //注册失败
                session.setAttribute("registerMessage", "服务器维护中");
                req.getRequestDispatcher("/views/register.jsp").forward(req, resp);
            }

        } catch (Exception e) {
            session.setAttribute("registerMessage", "服务器维护中");
            req.getRequestDispatcher("/views/register.jsp").forward(req, resp);
        }


    }
}
